package com.hdcx.Minfresh.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.util.RecyclerViewStateUtils;
import com.github.jdsjlzx.view.LoadingFooter;
import com.google.gson.Gson;
import com.hdcx.Minfresh.R;
import com.hdcx.Minfresh.adapter.ChangePointAdapter;
import com.hdcx.Minfresh.bean.OrderDetailWrapper;
import com.hdcx.Minfresh.model.DiYongQuan;
import com.hdcx.Minfresh.url.MyUrl;
import com.hdcx.Minfresh.util.AppUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/11/18.
 */

public class PointChangeActivity extends BaseActivity {
    ChangePointAdapter adapter;
//    PointChangeOrderListAdapter adapter2;
    LRecyclerView recyclerView;
//    LRecyclerView recyclerView2;
    LRecyclerViewAdapter mLRecyclerViewAdapter;
    Boolean isRefresh = false;
    Boolean isRefresh2 = false;
    int num = 1;
    int num2 = 1;
    int totleNum;
    int totleNum2;
    DiYongQuan data;
    OrderDetailWrapper data2;
//    View[] lines;
    int line_tag = 0;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_goodlist);
        initView();
        initData();
    }

    private void initView() {
        recyclerView = (LRecyclerView) findViewById(R.id.recycler_view);
//        recyclerView2 = (LRecyclerView) findViewById(R.id.recycler_view2);
        findViewById(R.id.tv_left).setOnClickListener(this);
        ((TextView) findViewById(R.id.tv_title)).setText("积分兑换");
//        View[] layouts = new View[]{findViewById(R.id.layout_1), findViewById(R.id.layout_2)};
//        lines = new View[]{findViewById(R.id.tv_line1), findViewById(R.id.tv_line2)};
//        for (int i = 0; i < layouts.length; i++) {
//            final int finalI = i;
//            layouts[i].setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    lines[line_tag].setVisibility(View.GONE);
//                    lines[finalI].setVisibility(View.VISIBLE);
//                    line_tag = finalI;
//                    if (line_tag == 0) {
//                        post_main();
//                        recyclerView2.setVisibility(View.GONE);
//                        recyclerView.setVisibility(View.VISIBLE);
//                    } else {
//                        post_main_history();
//                        recyclerView.setVisibility(View.GONE);
//                        recyclerView2.setVisibility(View.VISIBLE);
//                    }
//                }
//
//            });
//        }
    }

    /*   uid		用户id
       type	//分类 可选  默认全部  1未配送  2已配送*/
    private void post_main_history() {
        AppUtil.showLoading(this);
        JSONObject json = new JSONObject();
        try {
            json.put("uid", AppUtil.getUserId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.ORDERSCORE)
                .content(json.toString())
                .build()
                .execute(new Callback<OrderDetailWrapper>() {
                    @Override
                    public OrderDetailWrapper parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        return new Gson().fromJson(json, OrderDetailWrapper.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(OrderDetailWrapper response) {
                        AppUtil.closeLoading();
                        if (response.getStatus() == 1) {
                            totleNum2 = response.getCount();
                            if (num2 == 1) {
                                data2 = response;
//                                adapter2.setData(response);
                            } else {
                                data2.getList().addAll(response.getList());
//                                adapter2.setData(data2);
                            }
                        }
                        if (isRefresh2) {
//                            recyclerView2.refreshComplete();
                        }
                    }
                });
    }

    private void initData() {
        adapter = new ChangePointAdapter(this);
//        adapter2 = new PointChangeOrderListAdapter(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
//        recyclerView2.setLayoutManager(new LinearLayoutManager(this));
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        recyclerView.setAdapter(mLRecyclerViewAdapter);
//        recyclerView2.setAdapter(new LRecyclerViewAdapter(adapter2));
//        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
//            @Override
//            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
//                super.getItemOffsets(outRect, view, parent, state);
//                if (parent.getChildPosition(view) % 1 != 0) {
//                    outRect.right = 8;
//                }
//                outRect.top = 8;
//
//            }
//        });
        setRecycler();
        post_main();
    }

    private void setRecycler() {
        recyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                num = 1;
                isRefresh = true;
                post_main();
            }
        });
        recyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (num * 10 < totleNum) {
                    // loading more
                    num = num + 1;
                    RecyclerViewStateUtils.setFooterViewState(PointChangeActivity.this, recyclerView, 10, LoadingFooter.State.Loading, null);
                    post_main();
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(PointChangeActivity.this, recyclerView, 10, LoadingFooter.State.TheEnd, null);

                }
            }
        });
//        recyclerView2.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                num2 = 1;
//                isRefresh2 = true;
//                post_main_history();
//            }
//        });
//        recyclerView2.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore() {
//                if (num2 * 10 < totleNum) {
//                    // loading more
//                    num2 = num2 + 1;
//                    RecyclerViewStateUtils.setFooterViewState(PointChangeActivity.this, recyclerView2, 10, LoadingFooter.State.Loading, null);
//                    post_main_history();
//                } else {
//                    //the end
//                    RecyclerViewStateUtils.setFooterViewState(PointChangeActivity.this, recyclerView2, 10, LoadingFooter.State.TheEnd, null);
//
//                }
//            }
//        });
    }


    /* 请求参数
     class	分类id
     page	页码
     size    每页数量  可选
     all=1   上级分类下的所有商品  可选  分类筛选*/
  /*  价格排序 可选
    px=1    低到高
            px=2	高到低

    筛选	可选
    ps=0  明日配送 默认
    ps=1	后天配送
            ps=2	大后天配送
            价格
    bt=0,4   0表示不限*/
    private void post_main() {
        AppUtil.showLoading(this);
        JSONObject json = new JSONObject();
        try {
            json.put("page", num);
            json.put("uid", AppUtil.getUserId());
            json.put("size", "10");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.ULIST)
                .content(json.toString())
                .build()
                .execute(new Callback<DiYongQuan>() {
                    @Override
                    public DiYongQuan parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        Log.e("PointChangeActivity", "PointChangeActivity--parseNetworkResponse--兑换卷"+json);
                        return new Gson().fromJson(json, DiYongQuan.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(DiYongQuan response) {
                        AppUtil.closeLoading();
                        if (response.getStatus() == 1) {
                            totleNum = response.getCount();
                            if (num == 1) {
                                data = response;
                                adapter.setData(response);
                            } else {
                                data.getList().addAll(response.getList());
                                adapter.setData(data);
                            }
                        }
                        if (isRefresh) {
                            recyclerView.refreshComplete();
                        }
                    }
                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_left:
                finish();
                break;
        }
    }

    @Override
    public void onMyItemClick(final Object data) {

        AlertDialog dialog =  new AlertDialog.Builder(this).setTitle("确认")//设置对话框标题
                .setMessage("确定兑换？")//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        post_updata((String) data);
                    }
                }).show();//在按键响应事件中显示此对话框
    }

    private void post_updata(String data) {
        AppUtil.showLoading(this);
        JSONObject json = new JSONObject();
        try {
            json.put("uid", AppUtil.getUserId());
            json.put("id", data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.CONVERT)
                .content(json.toString())
                .build()
                .execute(new Callback<OrderDetailWrapper>() {
                    @Override
                    public OrderDetailWrapper parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        return new Gson().fromJson(json, OrderDetailWrapper.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(OrderDetailWrapper response) {
                        AppUtil.closeLoading();
                        if (response.getStatus() == 1) {
                            Toast.makeText(PointChangeActivity.this,"兑换成功！",Toast.LENGTH_SHORT).show();
                            post_main();
                        }

                    }
                });
    }
}